import axios from "axios";
import store from '@/store'
import Message from "element-ui/packages/message/src/main";
import MessageBox from "element-ui/packages/message-box/src/main";

const qs = require('qs')

const instance = axios.create({
    baseURL: '/api',
    withCredentials: true
})
let flag = true;
// 返回数据拦截处理
instance.interceptors.response.use(res => {
    if (res.data instanceof Blob) {
        return res.data
    }
    if (res.status === 200) {
        const _data = res.data
        if (_data && _data.success === true) {
            const {data, total, time} = _data
            if (total === null || total === undefined || total === '') {
                return data
            } else {
                return {data, total}
            }
        } else if (_data && _data.code === 403) {
            if (flag) {
                loginOut();
                flag = false
            }
        } else if (_data && _data.code !== 0) {
            Message.warning({
                message: _data.message,
                offset: 100,
                customClass: 'zZindex'
            })
            return Promise.reject(res.data)
        }
        const {data, total, time} = _data
        if (total === null || total === undefined || total === '') {
            return data
        } else {
            return {data, total}
        }
    } else {
        return Promise.reject(res.data)
    }
}, error => {
    if (error.response && error.response.status === 401) {
        if (flag) {
            loginOut();
            flag = false
        }
    } else {
        return Promise.reject(error.response)
    }
})

export const post = (url, data) => {
    addToken(instance)
    return instance.post(url, data)
}

export const get = (url, data) => {
    addToken(instance)
    return instance.get(url, {params: data})
}

export const addToken = (instance) => {
    instance.defaults.headers.common['Authorization'] = store.state.user.token || ''
    instance.defaults.headers.post['Content-Type'] = 'application/json'
}

const loginOut = () => {
    MessageBox.alert(
        `<div class="confirm-dialog">
			当前会话已过期，请重新登录
		</div>`,
        '提示',
        {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
        },
    ).then(async () => {
        await store.dispatch('_logout')
    })
}